package com.huoyun.userAdmin.action;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

//import javax.enterprise.inject.New;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.ServletActionContext;
import org.springframework.security.authentication.encoding.PasswordEncoder;

import com.huoyun.base.action.BaseAction;
import com.huoyun.userAdmin.bean.UserDetail;
import com.huoyun.userAdmin.service.UserDetailService;
import com.huoyun.user.service.UserService;
import com.huoyun.util.DateUtil;
import com.huoyun.util.FileUtil;
import com.huoyun.util.StringUtil;

public class AccountAction extends BaseAction {

	private static final Log log = LogFactory.getLog(AccountAction.class);
	
	private UserService userService;
	
	private UserDetailService userDetailService;
	
	private PasswordEncoder passwordEncoder;
	
	/**
	 * 老密码
	 */
	private String oldPassword;
	
	/**
	 * 新密码
	 */
	private String newPassword;
	
	/**
	 * 确认密码
	 */
	private String verifyPassword;
	
	/**
	 * 用户上传的头像文件
	 */
	private File avatarFile;
	
	/**
	 * 用户上传的头像文件名称
	 */
	private String avatarFileFileName;
	
	/**
	 * 用户头像截取的尺寸
	 */
	private String imgSize;
	
	/**
	 * 没有截取之前的用户头像路径
	 */
	private String avatarUrl;
	
	/**
	 * 用户对象
	 */
	private UserDetail userDetail;


	
	public String preChangePassword()
	{
		return SUCCESS;
	}
	
	public String changePassword()
	{
		oldPassword = passwordEncoder.encodePassword(oldPassword, getLoginUser().getSalt());
		if(getLoginUser().getPassword().equals(oldPassword))
		{
			newPassword = passwordEncoder.encodePassword(newPassword, getLoginUser().getSalt());
			userService.changePassword(getLoginUser().getId(), newPassword);
			
			getLoginUser().setPassword(newPassword);
			
			this.setResultMsg("密码修改成功");
		}
		else
		{
			this.setResultMsg("旧密码输入错误");
			return INPUT;
		}
		
			
		return SUCCESS;
	}
	
	public String preEditUserInfo()
	{
		try
		{
			userDetail = userDetailService.getUserDetailByUserId(getLoginUser().getId());
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		
		return SUCCESS;
	}
	
	public String editUserInfo()
	{
		this.setResultMsg("用户信息保存成功");
		
		try
		{
			userDetail.setUserId(getLoginUser().getId());
			
			userDetailService.updateUserBaseInfo(userDetail);
		}
		catch (Exception e) {
			this.setResultMsg("用户信息保存失败");
		}
		
		return SUCCESS;
	}
	
	public String preEditUserContact()
	{
		try
		{
			userDetail = userDetailService.getUserDetailByUserId(getLoginUser().getId());
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		return SUCCESS;
	}
	
	public String editUserContact()
	{
		this.setResultMsg("用户联系方式信息保存成功");
		
		try
		{
			userDetail.setUserId(getLoginUser().getId());
			
			userDetailService.updateUserContactInfo(userDetail);
		}
		catch (Exception e) {
			this.setResultMsg("用户联系方式信息保存失败");
		}
		
		return SUCCESS;
	}
	
	
	public void uploadAvatar() throws IOException
	{
		ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");  
        ServletActionContext.getResponse().setCharacterEncoding("utf-8");  
		String url = "";
		this.setResultMsg("");
		
		String path = FileUtil.TEMP_UPLOAD_AVATAR_DIR + "/" + DateUtil.getCurrentDate();
		String saveFolderPath = ServletActionContext.getRequest().getRealPath(path);  
		
		File saveFolder = new File(saveFolderPath);
		
		if (!saveFolder.exists())
		{
			saveFolder.mkdir();
		}
		File saveFile = new File(saveFolderPath, UUID.randomUUID().toString() + "." + StringUtil.getLastName(avatarFileFileName)); 
		
		try {
			FileUtil.copyFile(avatarFile, saveFile);
			
			url = path + "/" + saveFile.getName();
		} catch (Exception e) {
			this.setResultMsg("文件上传失败！");
		}
        
		ServletActionContext.getResponse().getWriter().print("{\"msg\":\""+this.getResultMsg()+"\",\"url\":\"" + url +"\"}");  
        ServletActionContext.getResponse().getWriter().flush();  
        ServletActionContext.getResponse().getWriter().close();  
    
	}
	
	public String preEditAvatar()
	{
		return SUCCESS;
	}
	
	public String editAvatar()
	{
		String[] imgSizes = imgSize.split(",");
		String path = FileUtil.UPLOAD_AVATAR_DIR + "/" + DateUtil.getCurrentDate();
		String saveFolderPath = ServletActionContext.getRequest().getRealPath(path);  
		
		File saveFolder = new File(saveFolderPath);
		
		if (!saveFolder.exists())
		{
			saveFolder.mkdir();
		}
		
		File oldFile = new File(ServletActionContext.getRequest().getRealPath("") + avatarUrl);
		
		try 
		{
			File newFile = FileUtil.cutting(oldFile, oldFile.getName(), saveFolderPath, Integer.parseInt(imgSizes[0]), Integer.parseInt(imgSizes[1]),
					Integer.parseInt(imgSizes[2]) - Integer.parseInt(imgSizes[0]), Integer.parseInt(imgSizes[3]) - Integer.parseInt(imgSizes[1]));
			
			userService.updateAvatarByUserId(getLoginUser().getId(), path + "/" + newFile.getName());
			
			getLoginUser().setUserImg(path + "/" + newFile.getName());
			
		} 
		catch (NumberFormatException e) 
		{
			this.setResultMsg("提交数据有误，请重新操作");
			return INPUT;
		} 
		catch (Exception e) 
		{
			this.setResultMsg("更新头像失败");
			log.error("用户头像更新失败，原因：" + e.fillInStackTrace());
			e.printStackTrace();
		}
		return SUCCESS;
	}
	
	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public PasswordEncoder getPasswordEncoder() {
		return passwordEncoder;
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	public String getOldPassword() {
		return oldPassword;
	}

	public void setOldPassword(String oldPassword) {
		this.oldPassword = oldPassword;
	}

	public String getNewPassword() {
		return newPassword;
	}

	public void setNewPassword(String newPassword) {
		this.newPassword = newPassword;
	}

	public String getVerifyPassword() {
		return verifyPassword;
	}

	public void setVerifyPassword(String verifyPassword) {
		this.verifyPassword = verifyPassword;
	}

	public File getAvatarFile() {
		return avatarFile;
	}

	public void setAvatarFile(File avatarFile) {
		this.avatarFile = avatarFile;
	}

	public String getAvatarFileFileName() {
		return avatarFileFileName;
	}

	public void setAvatarFileFileName(String avatarFileFileName) {
		this.avatarFileFileName = avatarFileFileName;
	}

	public String getImgSize() {
		return imgSize;
	}

	public void setImgSize(String imgSize) {
		this.imgSize = imgSize;
	}

	public String getAvatarUrl() {
		return avatarUrl;
	}

	public void setAvatarUrl(String avatarUrl) {
		this.avatarUrl = avatarUrl;
	}

	public UserDetail getUserDetail() {
		return userDetail;
	}

	public void setUserDetail(UserDetail userDetail) {
		this.userDetail = userDetail;
	}

	public UserDetailService getUserDetailService() {
		return userDetailService;
	}

	public void setUserDetailService(UserDetailService userDetailService) {
		this.userDetailService = userDetailService;
	}

}
